﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using SoufunData.DB;

namespace SoufunData
{
    public partial class ExToDbZAdvertising : DevExpress.XtraEditors.XtraForm
    {
        public ExToDbZAdvertising()
        {
            InitializeComponent();
        }

        private void btn_excelPath_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            openFileDialog1.Filter = "Excel文件|*.xls;*.xlsx";
            openFileDialog1.FileName = "";
            openFileDialog1.ShowDialog();
            string fileName = openFileDialog1.FileName;
            btn_excelPath.Text = fileName;

            gridControl2.DataSource = null;
            gridView2.Columns.Clear();
            gridView2.GroupPanelText = "请选择Excel文件";
            if (fileName == "")
            {
                return;
            }
            DataSet ds = Common.LoadDataFromExcel(fileName);
            if (ds == null || ds.Tables.Count == 0)
            {
                string strError = "读取Excel时发生错误，请核对：\r\n ";
                strError += "1，导入时请在Excel中关闭想要导入的文件！\r\n";
                strError += "2，导入的Excel表中的工作表名称必须为Sheet1,否者程序无法读取！\r\n";
                strError += "3，请确保您的计算机安装了Microsoft Office！\r\n";
                strError += "4，请确保导入的Excel文件正常！";
                XtraMessageBox.Show(strError);
                btn_excelPath.Text = "";
                return;
            }
            if (!CheckExcelColumnsName(ds.Tables[0]))
            {
                btn_excelPath.Text = "";
                return;
            }
            gridControl2.DataSource = ds.Tables[0];
            gridView2.GroupPanelText = "共有" + ds.Tables[0].Rows.Count + "条数据";
        }


        private void AddData()
        {
           
            DataTable dtOld = (DataTable)gridControl2.DataSource;

            DataTable dt = dtOld.Copy();
            dt.Rows.Clear();
            foreach (DataRow dataRow in dtOld.Rows)
            { 
                dt.Rows.Add(dataRow.ItemArray);
            }
             
            int insertRowsCount = 500;//一次性插入数据库行数
            int succeedrows = 0;//成功插入数据行数
            StringBuilder strSql = new StringBuilder();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow row = dt.Rows[i];
                string strProName = row["项目名称"].ToString();
                string strXzq = row["行政区"].ToString();
                string strPubTime = row["广告投放日期"].ToString();
                string strPubMedia = row["投放媒体"].ToString();
                string strPubArea= row["投放版幅"].ToString();
                string strPubPage = row["投放版面"].ToString();
                string strTheme = row["推广主题"].ToString();
                string strSaleInfo = row["销售信息"].ToString();
                string strProType = row["物业形态"].ToString();
                string strType = row["类型"].ToString();
                string strImage = row["电子附图"].ToString();                 
                if (i % insertRowsCount == 0)
                {
                    strSql = new StringBuilder();
                    strSql.Append("Insert into tZAdvertising (");
                    strSql.Append("ProjectName,");
                    strSql.Append("AdministratiVeregion,");
                    strSql.Append("PublicTime,");
                    strSql.Append("PublicMedia,");
                    strSql.Append("PublicArea,");
                    strSql.Append("PublicPage,");
                    strSql.Append("PromotionTheme,");
                    strSql.Append("SaleInfo,");
                    strSql.Append("PropertyType,");
                    strSql.Append("Type,");
                    strSql.Append("Image)");                    
                    strSql.Append(" value  ");
                }
                strSql.Append("(");
                strSql.Append("'");
                strSql.Append(strProName);
                strSql.Append("','");
                strSql.Append(strXzq);
                strSql.Append("','");
                strSql.Append(strPubTime);
                strSql.Append("','");
                strSql.Append(strPubMedia);
                strSql.Append("','");
                strSql.Append(strPubArea);
                strSql.Append("','");
                strSql.Append(strPubPage);
                strSql.Append("','");
                strSql.Append(strTheme);
                strSql.Append("','");
                strSql.Append(strSaleInfo);
                strSql.Append("','");
                strSql.Append(strProType);
                strSql.Append("','");
                strSql.Append(strType);
                strSql.Append("','");
                strSql.Append(strImage);
                strSql.Append("'),");

                if ((i + 1) % insertRowsCount == 0
                    || i == dt.Rows.Count - 1)
                {
                    strSql.Remove(strSql.Length - 1, 1);
                    try
                    {
                        succeedrows += DbHelper.ExecuteSql(strSql.ToString());
                    }
                    catch (Exception ex)
                    {
                        XtraMessageBox.Show(ex.Message);
                    }

                }
            }

            if (dt.Rows.Count == succeedrows)
            {
                XtraMessageBox.Show("添加成功！");
                BeginInvoke(new MethodInvoker(() =>
                {
                    btn_excelPath.Text = "";
                    gridControl2.DataSource = null;
                    gridView2.GroupPanelText = "请选择想要导入的Excel表！";
                }));
            }
            else
            {
                int failedCount = dt.Rows.Count - succeedrows;
                XtraMessageBox.Show("共记" + dt.Rows.Count + "条数据，其中"
                    + failedCount + "条数据添加失败！");
            }
            BeginInvoke(new MethodInvoker(() =>
            {
               
                btn_excelPath.Enabled = true;
                btn_add.Enabled = true;
            }));
        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            if (btn_excelPath.Text.Trim()=="")
            {
                XtraMessageBox.Show("请先选择Excel！");
                return;
            }
            if (!CheckDataValid())
            {
                return;
            }
             
            btn_excelPath.Enabled = false;
            btn_add.Enabled = false;
            Thread t = new Thread(AddData) { IsBackground = true };
            t.Start();
        }

        #region 数据完整性检测
        private bool CheckDataValid()
        {
            DataTable dt = (DataTable)gridControl2.DataSource;
            StringBuilder strErrors = new StringBuilder();
           
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                string strProName = dr["项目名称"].ToString();
                string strXzq = dr["行政区"].ToString();
                string strPubTime = dr["广告投放日期"].ToString();
                if (strProName.Trim() == "")
                {
                    strErrors.Append("第"+(i+1)+"行数据中的【项目名称】为空！\r\n"); 
                }
                if (strXzq.Trim()=="")
                {
                    strErrors.Append("第" + (i + 1) + "行数据中【行政区】未填！\r\n");
                }
                //strPubTime = strPubTime.Replace("年","/").
                //    Replace("月","/").Replace("日","")+" 00:00:00";
                DateTime pubTime = new DateTime();
                if (!DateTime.TryParse(strPubTime,out pubTime))
                {
                    strErrors.Append("第" + (i + 1) 
                   + "行数据中【广告投放日期】的数据格式有误，应为时间格式【yyyy年MM月dd日】！\r\n");
                }
            }
            if (strErrors.ToString() != "")
            {                
                XtraMessageBox.Show("您选择的Excel中的数据存在以下错误：\r\n"+
                    strErrors);
                return false;
            }              
            return true;
        }
         
        private bool CheckExcelColumnsName(DataTable dt)
        {
            StringBuilder strErrors = new StringBuilder();
            if (!dt.Columns.Contains("项目名称"))
            {
                strErrors.Append("【项目名称】、");
            }
            if (!dt.Columns.Contains("行政区"))
            {
                strErrors.Append("【行政区】、");
            }
            if (!dt.Columns.Contains("广告投放日期"))
            {
                strErrors.Append("【广告投放日期】、");
            }
            if (!dt.Columns.Contains("投放媒体"))
            {
                strErrors.Append("【投放媒体】、");
            }
            if (!dt.Columns.Contains("投放版幅"))
            {
                strErrors.Append("【投放版幅】、");
            }
            if (!dt.Columns.Contains("投放版面"))
            {
                strErrors.Append("【投放版面】、");
            }
            if (!dt.Columns.Contains("推广主题"))
            {
                strErrors.Append("【推广主题】、");
            }
            if (!dt.Columns.Contains("销售信息"))
            {
                strErrors.Append("【销售信息】、");
            }
            if (!dt.Columns.Contains("物业形态"))
            {
                strErrors.Append("【物业形态】、");
            }
            if (!dt.Columns.Contains("类型"))
            {
                strErrors.Append("【类型】、");
            }
            if (!dt.Columns.Contains("电子附图"))
            {
                strErrors.Append("【电子附图】");
            }
            if (strErrors.ToString() != "")
            {
                XtraMessageBox.Show("您选择的广告投放Excel表数据不正常,缺少以下数据列:\r\n" +
                                    strErrors);
                return false;
            }
            return true;
        }
        #endregion
    }
}